package com.bipbip.repositorio;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.bipbip.modelo.NotificacionStandard;
import com.bipbip.modelo.Usuario;

@Repository(value = "notificacionDao")
@Transactional(readOnly = true)
public class JPANotificacionDAOImpl implements NotificacionDAO {

	private EntityManager em = null;

	/*
	 * Sets the entity manager.
	 */
	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public NotificacionStandard insert(NotificacionStandard notificacionStandard) {
		em.persist(notificacionStandard);
		return notificacionStandard;
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public void delete(NotificacionStandard notificacionStandard) {
		notificacionStandard.setDeleted(true);
		update(notificacionStandard);
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public NotificacionStandard update(NotificacionStandard notificacionStandard) {
		return em.merge(notificacionStandard);
	}

	public NotificacionStandard select(int id) {
		return em.find(NotificacionStandard.class, id);
	}

	public List<NotificacionStandard> selectAll() {
		return em.createQuery("select n from NotificacionStandard n")
				.getResultList();
	}

	public List<NotificacionStandard> selectByUsuario(Usuario usuario) {
		Query query = em
				.createQuery("select n from NotificacionStandard n where usuario = "
						+ usuario.getId()
						+ " and isDeleted=0 order by fecha desc");
		return query.getResultList();
	}

	public List<NotificacionStandard> selectByIdUsuario(Integer idUsuario) {
		Query query = em
				.createQuery("select n from NotificacionStandard n where usuario = "
						+ idUsuario + " and isDeleted=0 order by fecha desc");
		return query.getResultList();
	}

}
